import React, { useEffect } from "react";
import { useLocation, useNavigate, Location } from "react-router-dom";
import { Button, Card, Form, Input, message } from "antd";
import type { addHospitalSetParamsType } from "@/api/hospital/model/hospitalSetTypes";
import {
  addHospitalSetRequest,
  getHosSetFormIdRequest,
  updateHospitalRequest,
} from "@/api/hospital/hospitalSet";

import style from "../index.module.css";

import girl from "./girl.png";
export default function AddOfUpdateHospital() {
  function useMyLocation<T>() {
    type L = Location & { state?: T };
    return useLocation() as L;
  }
  //使用可选链操作符取值，取的到就取，取不到id就是undefined
  const  id  = useMyLocation<{ id: number }>().state?.id
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useEffect(() => {
    //如果没取到id，说明是从添加按钮跳转进来的，那就不执行添加表单的默认字段
    if (!id) return 
    const getHosForm = async () => {
      const re = await getHosSetFormIdRequest(id)
      form.setFieldsValue(re)
    };
    getHosForm()
  }, []);

  const addHospitalHandle = async (fieldValue: addHospitalSetParamsType) => {
    if (!id) {
      await addHospitalSetRequest(fieldValue);
    }else{
      await updateHospitalRequest({...fieldValue,id})
    }
    navigate(-1);
    message.success(id?'更新成功':'添加成功')
  };

  return (
    <div>
      <Card title="请输入医院信息">
        <Form
          style={{ background: `url(${girl}) no-repeat center right/contain` }}
          name="basic"
          wrapperCol={{ span: 10 }}
          labelCol={{ span: 3 }}
          autoComplete="off"
          form={form}
          onFinish={addHospitalHandle}
        >
          <Form.Item name="hosname" label="医院名称">
            <Input />
          </Form.Item>

          <Form.Item name="hoscode" label="医院编号">
            <Input />
          </Form.Item>
          <Form.Item name="apiUrl" label="api基础路径">
            <Input />
          </Form.Item>
          <Form.Item name="contactsName" label="联系人姓名">
            <Input />
          </Form.Item>
          <Form.Item name="contactsPhone" label="联系人手机">
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 5 }}>
            <Button type="primary" htmlType="submit" className={style.mr}>
              提交
            </Button>
            <Button type="default" htmlType="button">
              返回
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
